<template>
  <el-dialog v-model="boxVisible" width="70%">
    <el-row :gutter="20">
      <el-col :span="16" style="border-right: 1px solid rgb(183 180 180 / 0.34)">
        <p class="title-p">警情信息</p>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属杆塔:">
              <span class="item-text">{{ dataBasicsForm.stationName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="传感类别:">
              <span class="item-text">{{ dataBasicsForm.businessType }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="dataBasicsForm.componentId">
            <el-form-item label="传感ID:">
              <span class="item-text">{{ dataBasicsForm.componentId }}</span>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="通道预置位:">-->
          <!--              <span class="item-text">{{ dataBasicsForm.channelNo }}-{{ dataBasicsForm.presettingNo }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="预警类型:">
              <span class="item-text">{{ dataBasicsForm.type }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预警数值:">
              <span class="item-text" style="color: #ce1010;font-size: 18px">{{ dataBasicsForm.warnNum }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上传时间:">
              <span class="item-text">{{ dataBasicsForm.uploadDate }}</span>
            </el-form-item>
          </el-col>

          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="保存时间:">-->
          <!--              <span class="item-text">{{ dataBasicsForm.createDate }}</span>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12" v-if="dataBasicsForm.warningType">
            <el-form-item label="告警类型:">
              <el-tag style="margin-right: 4px;margin-bottom: 2px" type="warning" size="small" effect="plain"
                      v-for="(item ,index) in warningTypeArr(dataBasicsForm.warningType)" :key="index">
                {{ getDictLabel("waring_type", item) }}
              </el-tag>
              <!--                <span class="item-text">{{ getDictLabel("kx_img_alarm_level", dataBasicsForm.level) }}</span>-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处理状态:" prop="deviceName">
              <span class="item-text">
              {{ getDictLabel("processing_status", dataBasicsForm.processingStatus) }}
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="dataBasicsForm.processingStatus != 'processNotStart'">
            <el-form-item label="处理方式:" prop="deviceName">
              <span class="item-text">
               {{ getDictLabel("level", dataBasicsForm.level) }}
                <!--              {{ getDictLabel("processing_status", dataBasicsForm.processingStatus) }}-->
              </span>
            </el-form-item>
          </el-col>

          <el-col :span="24" v-if="dataBasicsForm.processingStatus == 'processNotStart'">
            <div style="display: flex;align-items: center">
              <span class="item-text">处理方式：</span>
              <!--              <el-button class="level-sz" type="warning" round @click="handleClose(0)">忽略</el-button>-->
              <!--              <el-button class="level-sz" style="background-color: #e00606; color: aliceblue" @click="handleClose(1)" round>告警处理</el-button>-->
              <el-radio-group v-model="disposeFrom.level" style="margin-right: 20px">
                <el-radio-button label="误报" :value="-1"/>
                <el-radio-button label="忽略" :value="0"/>
                <el-radio-button label="告警处理" :value="1"/>
              </el-radio-group>
              <el-select v-if="disposeFrom.level === 1" v-model="disposeFrom.nextUserId"
                         placeholder="选择处理人员" style="width: 240px">
                <el-option
                    v-for="item in disposeOptions"
                    :key="item.id"
                    :label="item.realName"
                    :value="item.id"
                />
              </el-select>
            </div>
          </el-col>

          <el-col :span="24" style="text-align: center" v-if="dataBasicsForm.processingStatus == 'Processing'">
            <el-button style="padding: 0 50px" type="warning" @click="disposeVisible = true">去处理</el-button>
          </el-col>
        </el-row>
      </el-col>

      <el-col :span="8">
        <p class="title-p">处警经过</p>
        <el-empty v-if="flowList.length == 0" description="暂无流程"/>
        <el-timeline style="width: 100%">
          <el-timeline-item color="#0bbd87" v-for="(item,index) in flowList" :key="index" :timestamp="item.endTime"
                            placement="top">
            <el-card style="border: 1px solid rgb(183 180 180 / 0.34) ">
              <h4>{{ item.activityName }}</h4>
              <p v-if="item.assigneeName != null">{{ index == 0 ? "发起人" : "操作人" }}：{{ item.assigneeName }}</p>
              <p v-if="item.activityName === '运检人员处理'">
                <el-image v-for="(i,imgIndex) in processImgs" :key="imgIndex" class="flow-imgs-p" :src="i"
                          :initial-index="imgIndex" :preview-src-list="processImgs"></el-image>
              </p>
              <p v-if="item.comment != null">备 注：{{ item.comment }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </el-col>
    </el-row>
    <template v-slot:footer>
      <el-button @click="boxVisible = false">{{ $t("cancel") }}</el-button>
      <el-button v-if="dataBasicsForm.processingStatus == 'processNotStart'" type="primary"
                 @click="alarmHandlebusiness()">{{ $t("confirm") }}
      </el-button>
      <el-button v-else-if="dataBasicsForm.processingStatus =='processing' && flowView =='processing'" type="primary"
                 @click="dispose()">处理
      </el-button>
    </template>
  </el-dialog>


  <!--  处理告警-->
  <el-dialog v-model="disposeVisible" title="处理告警" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef"
             :label-width="$i18n.locale === 'en-US' ? '160px' : '120px'">
      <el-form-item label="处理方案">
        <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 8 }" maxlength="300" show-word-limit
                  v-model="dataForm.handleContent"></el-input>
      </el-form-item>
      <el-form-item label="处理图片文件">
        <AutoUploadFile :action="uploadUrl" :data="datas" @change="change"></AutoUploadFile>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="disposeVisible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="alarmHandleComplete()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>


  <!--  处理方式-->
  <el-dialog v-model="disposeDialogVisible" title="处理预警" :width="600">
    <el-select v-model="disposeFrom.nextUserId" placeholder="选择处理人员" style="width: 240px">
      <el-option
          v-for="item in disposeOptions"
          :key="item.id"
          :label="item.realName"
          :value="item.id"
      />
    </el-select>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="disposeDialogVisible = false">{{ $t("cancel") }}</el-button>
        <el-button type="primary" @click="disposeOk()">
          {{ $t("confirm") }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import useView from "@/hooks/useView";
import {IObject} from "@/types/interface";
import baseService from "@/service/baseService";
import {defineComponent, reactive, toRefs} from "vue";
import {getToken} from "@/utils/cache";
import app from "@/constants/app";
import AutoUploadFile from "@/views/flow-warning/auto-upload-file.vue";

const warningTypeArr = (data: string) => {
  return data.split(",");
}

const dataBasicsForm = {
  id: "",
  picUrlMin: "",
  stationName: "",
  channelNo: "",
  presettingNo: "",
  createDate: "",
  updateDate: "",
  warningType: "",
  picUrl: "",
  ip: "",
  processingStatus: "",
  level: "",
  videoUrl: ""
}

const disposeFrom = {
  id: "",
  level: 77,
  nextUserId: ""
}

export default defineComponent({
  components: {
    AutoUploadFile
  },
  setup() {
    const state = reactive({
      boxVisible: false,
      listData: {} as any, //列表项原生参数
      dataBasicsForm: JSON.parse(JSON.stringify(dataBasicsForm)),
      dataForm: {
        id: "",
        taskId: "",
        processDefinitionId: "",
        processImgs: [],
        handleContent: ""
      },
      flowList: [] as any,
      disposeVisible: false as any,
      uploadUrl: `${app.api}/app/uploadFile?token=${getToken()}`,
      datas: {
        type: "WarningPictureFlow"
      },
      processImgs: [],
      disposeDialogVisible: false as any,
      disposeOptions: [],
      disposeFrom: JSON.parse(JSON.stringify(disposeFrom)),
      flowView: ""
    });
    return {...useView(state), ...toRefs(state), warningTypeArr};
  },
  computed: {
    dataRule(): IObject {
      return {
        handleContent: [{required: true, message: this.$t("validate.required"), trigger: "blur"}]
      };
    }
  },
  methods: {
    change(urls: any) {
      this.dataForm.processImgs = [];
      urls.forEach((i: any) => {
        this.dataForm.processImgs.push(i.data);
      });
      console.log(this.dataForm.processImgs);
    },
    init(data: any, floest: string) {
      this.boxVisible = true;
      console.log(data)
      this.$nextTick(() => {
        this.flowView = floest;
        this.listData = data;
        this.getWorkers();
        this.dataBasicsForm = JSON.parse(JSON.stringify(dataBasicsForm));
        this.disposeFrom = JSON.parse(JSON.stringify(disposeFrom));

        console.log("------", this.listData)
        this.getInfo(this.listData.businessKey !== undefined ? this.listData.businessKey : this.listData.id);
        // this.getFlow(this.listData.processInstanceId);
      });
    },
    // 获取表单详情信息
    getInfo(id: string) {
      baseService.get(`/KxSensorUnusual/kxsensorunusual/${id}`).then((res) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        }
        this.dataBasicsForm = res.data;
        this.getFlow(res.data.procInstId);
        if (res.data.handleUrls) {
          let imgs = res.data.handleUrls.split(";");
          this.processImgs = imgs.map((i: string) => {
            return this.imgUrl(i)
          })
        }
      });
      // baseService.get(`/KxSensorUnusual/kxsensorunusual/getWarinInfo?id=${id}`).then((res) => {
      //   if (res.code !== 0) {
      //     return this.$message.error(res.msg);
      //   }
      //   if (res.data.handleUrls) {
      //     let imgs = res.data.handleUrls.split(";");
      //     this.processImgs = imgs.map((i: string) => {
      //       return this.imgUrl(i)
      //     })
      //   }
      //
      //   console.log(this.processImgs);
      // });
    },
    // 获取流程信息
    getFlow(id: string) {
      if (id === null) {
        return;
      }
      baseService.get(`/flow/common/historic/list?processInstanceId=${id}`).then((res) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        }
        console.log(res.data)
        this.flowList = res.data;
      });
    },
    // 获取指派人员
    getWorkers() {
      baseService.get(`/sys/user/getByRoleId?id=123`).then((res) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        }
        this.disposeOptions = res.data;
      });
    },
    // 处理方式选择
    dataFormSubmitHandle() {
      (!this.dataForm.id ? baseService.post : baseService.put)("/KxStation/kxstation", this.dataForm).then((res) => {
        if (res.code !== 0) {
          let msg = res.msg;
          return this.$message({
            dangerouslyUseHTMLString: true,
            message: msg,
            type: "warning"
          });
        }
        this.$message({
          message: this.$t("prompt.success"),
          type: "success",
          duration: 500,
          onClose: () => {
            this.visible = false;
            this.$emit("refreshDataList");
          }
        });
      });
    },
    // 选择指派人员
    disposeOk() {
      if (this.disposeFrom.nextUserId == "") {
        return this.$message.error("请选择处理人员");
      }
      this.alarmHandlebusiness();
      this.disposeDialogVisible = false
    },
    // 处理
    dispose() {
      this.disposeVisible = true;
    },
    // 确定等级
    alarmHandlebusiness() {
      if (this.disposeFrom.level == 77) {
        return this.$message.error("请选择处理方式");
      }
      if (this.disposeFrom.level === 1 && this.disposeFrom.nextUserId == "") {
        return this.$message.error("请选择处理人员");
      }
      this.disposeFrom.id = this.dataBasicsForm.id;
      baseService.post("/KxSensorUnusual/kxsensorunusual/startProcess", this.disposeFrom).then((res) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        }
        this.$message({
          message: this.$t("prompt.success"),
          type: "success",
          duration: 500,
          onClose: () => {
            this.boxVisible = false;
            this.$emit("close", true);
          }
        });
      });
    },
    // 去处理
    alarmHandleComplete() {
      let params = {
        id: this.dataBasicsForm.id,
        taskId: this.listData.taskId,
        handleUrls: this.dataForm.processImgs.join(";"),
        handleContent: this.dataForm.handleContent
      };
      baseService
          .post("/KxSensorUnusual/kxsensorunusual/complete", params)
          .then((res) => {
            if (res.code !== 0) {
              this.$message.error(res.msg);
              return;
            }
            this.$message({
              message: this.$t("prompt.success"),
              type: "success",
              duration: 500,
              onClose: () => {
                this.disposeVisible = false;
                this.boxVisible = false;
                this.$emit("close", true);
              }
            });
          });
    },
    // 图片路径拼接
    imgUrl(url: string) {
      return `${app.api}/KxWarningPic/kxwarningpic/getImage?token=${getToken()}&filePath=` + url;
    },
    liveUrl(url: string) {
      return app.httpgb + "/" + url;
    }

  }
});
</script>

<style lang="scss" scoped>
.el-card {
  background-color: rgb(5, 20, 39);
  color: rgb(252, 252, 252);

}

.item-text {
  color: #FFFFFF;
}

.title-p {
  border-left: 4px solid #ffff00;
  padding-left: 10px;
  font-size: 16px;
  color: rgb(23, 180, 215);
  font-weight: 560;
}

.imgbox {
  width: 100%;
  height: 300px;
}

.flow-imgs-p {
  margin-right: 10px;
  width: 80px;
  height: 70px;
}
</style>
